# Copyright (C) 2009 Martin Kirsche

import time
import re
from eventio import * # http://www.ysbl.york.ac.uk/~emsley/coot/mbox-2004-2005/att-0547/eventio.py

class RemoteControl():
    commands = {
        '1/163/0':'skip',
        '1/164/0':'pause',
        '1/166/0':'stop',
        '1/115/0':'volup',
        '1/114/0':'voldown',
        '1/113/0':'mute',
        '1/104/0':'chup',
        '1/109/0':'chdown',
        '1/28/0':'ok',
        '1/105/0':'left',
        '1/106/0':'right',
        '1/103/0':'up',
        '1/108/0':'down',
        '1/79/0':'1',
        '1/80/0':'2',
        '1/81/0':'3',
        '1/75/0':'4',
        '1/76/0':'5',
        '1/77/0':'6',
        '1/71/0':'7',
        '1/72/0':'8',
        '1/73/0':'9',
        '1/82/0':'0',
        '1/55/0':'*',
    }
    player = None
    
    def __init__(self, path):
        self.fifo = [queue(d, 0.005) for d in path if re.match('^/dev/input/event\d+$', d)]
    
    def MainLoop(self):
        if self.player:
            self.player.play()
        while True:
            if self.player:
                time.sleep(self.player.poll()/1000.0)
            else:
                time.sleep(100/1000.0);
                
            for q in self.fifo:
                event = q.waitevent()
                if event == None: continue
                sec,usec,type,code,value = event
                c = '%d/%d/%d' % (type,code,value)
                if not self.player: print c
                if self.player and self.commands.has_key(c):       
                    if "stop" == self.commands[c]:
                        self.player.stop()
                        return
                    if "skip" == self.commands[c]:
                        self.player.skip()
                    if "pause" == self.commands[c]:
                        self.player.isPaused = not self.player.isPaused
                    if "ok" == self.commands[c]:
                        self.player.download()
    
def main():
    import sys
    remoteControl = RemoteControl(sys.argv[1:])
    remoteControl.MainLoop()
    
if __name__ == '__main__':
    main()
